package de.grosjohann.android.feuerwehr;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import de.grosjohann.android.feuerwehr.adapter.WeatherListAdapter;
import de.grosjohann.android.feuerwehr.domain.AbstractWarning;
import de.grosjohann.android.feuerwehr.notification.Notify;
import de.grosjohann.android.feuerwehr.panel.Panel;
import de.grosjohann.android.feuerwehr.service.IntentServiceFacade;
import de.grosjohann.android.feuerwehr.service.WeatherDisplayService;
import de.grosjohann.android.feuerwehr.service.WeatherNotificationService;
import de.grosjohann.android.feuerwehr.type.FireIndexType;
import de.grosjohann.android.feuerwehr.type.WeatherWarningType;
import de.grosjohann.android.feuerwehr.util.JSON2ObjectUtil;

public class WeatherActivity
  extends Activity
  implements OnItemClickListener, IUpdateUIListener {

  private static final String NAME = "WeatherActivity";
  private int orientation;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.weather);
    orientation = getResources().getConfiguration().orientation;

    ((TextView) findViewById(R.id.tvHeader)).setText(R.string.lblWeatherWarning);

    ListView lv = (ListView) findViewById(R.id.lvWeatherWarning);
    BaseAdapter baseAdapter = new WeatherListAdapter(this, R.layout.weatherwarning);
    lv.setAdapter(baseAdapter);

    lv.setTextFilterEnabled(false);
    lv.setDividerHeight(10);
    lv.setOnItemClickListener(this);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      Log.i(NAME, "started - has extras");
      updateUI((String) extras.get(WeatherNotificationService.WEATHER_DATA));
    }

    WeatherDisplayService.updateUIListener = this;
  }

  @Override
  protected void onResume() {
    super.onResume();
    Notify.getInstance().clear(this);

    IntentServiceFacade.startOnce(this, WeatherDisplayService.class);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.weather, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      case R.id.miWeatherInfo:
        startActivity(new Intent(this, WeatherInfoActivity.class));
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    AbstractWarning<?> warning = ((WeatherListAdapter) parent.getAdapter()).getItem(position);

    if (orientation == Configuration.ORIENTATION_PORTRAIT) {
      Intent intent = new Intent(this, WeatherDetailActivity.class);
      intent.putExtra(WeatherDetailActivity.WEATHER_OBJECT, warning);
      startActivity(intent);
    } else {

      LinearLayout llWarningDetail = (LinearLayout) findViewById(R.id.llWarningDetail);

      TextView tvWarningMsg = (TextView) llWarningDetail.findViewById(R.id.tvWarningMsg);
      tvWarningMsg.setText(warning.getMessage());
      TextView tvWarningDetail = (TextView) llWarningDetail.findViewById(R.id.tvWarningDetail);
      tvWarningDetail.setText(warning.getDetail());
    }
  }

  /*
   * Update of WeatherData.
   */
  @Override
  public void updateUI(final String newData) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        TextView tvNoWeatherWarning = (TextView) findViewById(R.id.tvNoWeatherWarning);
        LinearLayout llWeatherWarning = (LinearLayout) findViewById(R.id.llWeatherWarning);

        try {

          tvNoWeatherWarning.setVisibility(View.GONE);
          llWeatherWarning.setVisibility(View.VISIBLE);

          List<AbstractWarning<?>> list = new ArrayList<AbstractWarning<?>>();

          /*  Waldbrandindex */
          list.add(JSON2ObjectUtil.getFireIndex(newData));
          /* Liste der Wetter-Meldungen  */
          list.addAll(JSON2ObjectUtil.getWeatherWarningList(newData));

          ListView lv = (ListView) findViewById(R.id.lvWeatherWarning);
          ((WeatherListAdapter) lv.getAdapter()).addAll(list);

          if (orientation == Configuration.ORIENTATION_LANDSCAPE) {

            if (list.get(0).getLevel() != FireIndexType.SEHR_GERINGE_GEFAHR
                || list.get(1).getLevel() != WeatherWarningType.KEINE_WARNUNGEN) {
              TextView tvWarningDetail = (TextView) findViewById(R.id.tvWarningDetail);
              tvWarningDetail.setText(R.string.lblSelectWarning);
            }
          }

        } catch (JSONException ex) {
          Log.e(NAME, ex.getMessage(), ex);

          tvNoWeatherWarning.setVisibility(View.VISIBLE);
          llWeatherWarning.setVisibility(View.GONE);

          Panel panel = new Panel(getApplicationContext(), WeatherActivity.this);
          panel.showError(R.string.errReceiveWeatherData);
        }
      }
    });
  }

  @Override
  public void showInfo(String info) {
    // nothing to do
  }

  @Override
  public void showWarning(String warning) {
    // nothing to do
  }

  @Override
  public void showError(final String error) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Panel panel = new Panel(getApplicationContext(), WeatherActivity.this);
        panel.showError(error);
      }
    });

  }

}
